package es

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"strconv"
	"week_three/car_srv/common/global"
	"week_three/car_srv/models"
	car_rpc "week_three/car_srv/proto"
)

func CreateCarEs(index string, car *models.Car) bool {
	_, err := global.EsClient.Index().Index(index).Id(strconv.Itoa(int(car.ID))).BodyJson(car).Do(context.Background())
	if err != nil {
		return false
	}
	return true
}

func SearchEs(index string, name string) []*car_rpc.CarData {

	res, err := global.EsClient.Search().Index(index).Query(elastic.NewMultiMatchQuery(name, "Name", "Detail")).Do(context.Background())
	if err != nil {
		panic(err)
	}
	var maps []map[string]interface{}
	for _, v := range res.Hits.Hits {
		var m map[string]interface{}
		json.Unmarshal(v.Source, &m)
		for s, h := range v.Highlight {
			m[s] = h[0]
		}
		maps = append(maps, m)
	}
	var list []*car_rpc.CarData
	for _, m := range maps {
		var data = &car_rpc.CarData{
			Name:    m["Name"].(string),
			Price:   int32(m["Price"].(float64)),
			Brand:   m["Brand"].(string),
			CarType: int32(m["CarType"].(float64)),
			Detail:  m["Detail"].(string),
		}
		list = append(list, data)
	}
	return list
}
